<?php

namespace App\Console\Command;


use App\Service\Mychat;
use DI\Annotation\Inject;
use League\CLImate\CLImate;
use Monolog\Logger;
use Noodlehaus\Config;
use Predis\Client;
use Predis\Connection\ConnectionException;
use Psr\Log\LoggerInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wonfu\Core\AppConfig;
use Ratchet\WebSocket\WsServer as RatchetWsServer;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use React\EventLoop\Loop;

class RedisTest extends Command
{

    protected static $defaultName = 'Redis:test';

    /**
     * @Inject("appConfig")
     * @var AppConfig
     */
    private $appConfig;

    /**
     * @Inject
     * @var Config
     */
    private $envConfig;

    /**
     * @Inject()
     * @var Client
     */
    private $redis;

    /**
     * @Inject()
     * @var LoggerInterface
     */
    private $logger;


    protected function configure()
    {
        $this->setDescription('run websocket server.')
            ->setHelp('This command allows you to run your websocket server');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $climate = new CLImate();
        $climate->animation('hello')->enterFrom('right');
        $pid = getmypid();
        $climate->info("run in {$pid}");
        $redis = $this->redis;
        $timer = Loop::addPeriodicTimer(2, function ()use($redis) {
            $this->redisCheckHealth($redis);
            $this->logger->info("heartbeat");
        });
        dump($redis->get('foo'));
        dump($this->redisCheckHealth($redis));
        sleep(22);
        $cmdSet = $redis->createCommand('config', ['get', 'timeout']);
        $cmdSetReply = $redis->executeCommand($cmdSet);
        dump($cmdSetReply);
        return Command::SUCCESS;
    }

    /**
     * @param Client $redis
     */
    private function redisCheckHealth($redis)
    {
        try {
            if ($redis->ping("hello") == "hello") {
                return true;
            }
        } catch (ConnectionException $exception) {
            return false;
        }
        return false;
    }


}